import { Button, Card, Checkbox, Divider, Form, Input, Modal, Pagination, Space, Table } from 'antd'
import type { PaginationProps } from 'antd';
import React, { useEffect, useState } from 'react'
import { UserOutlined, FormOutlined, DeleteOutlined, SearchOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { getUserList, remove, update, save, toAssign, doAssign, type UserModel } from '@/api/users'
import { CheckboxChangeEvent } from 'antd/lib/checkbox';
import type { CheckboxValueType } from 'antd/es/checkbox/Group';

export default function User() {
  let [selectionType, setSelectionType] = useState<'checkbox' | 'radio'>('checkbox');

  let [userList, setUserList] = useState<UserModel[]>([])

  let [page, setPage] = useState(1)
  let [limit, setLimit] = useState(5)
  let [total, setTotal] = useState(0)
  let [username, setUsername] = useState('')
  let [inputVisible, setInputVisible] = useState(false)
  let [form] = Form.useForm()
  let [formData, setFormData] = useState({
    id: '',
    gmtCreate: '',
    gmtModified: '',
    deleted: false,
    password: '',
    salt: null,
    token: null,
    roleName: ''
  })
  let [isModalOpen, setIsModalOpen] = useState(false);

  let layout = {labelCol: { span: 4 }, wrapperCol: { span: 20 }};
  let showModal = () => {
    setIsModalOpen(true);
  };

  let handleOk = async () => {
    setIsModalOpen(false);
    let fields = form.getFieldsValue()
    let params = {
      ...formData,
      ...fields
    }
    if(inputVisible) {
      await save(fields)
    } else {
      await update(params)
    }
    getUserListAsync()
    setInputVisible(false)
  };

  let handleCancel = () => {
    setIsModalOpen(false);
    setInputVisible(false)
  };

  let addHandler = () => {
    setInputVisible(true)
    setIsModalOpen(true);
    form.setFieldsValue({
      username: '',
      nickName: '',
      password: ''
    })
  }

  let changeHandler = (e: any) => {
    setUsername(e.target.value)
  }

  let [isOpen, setIsOpen] = useState(false)
  let CheckboxGroup = Checkbox.Group;
  let [indeterminate, setIndeterminate] = useState(true);
  let [checkAll, setCheckAll] = useState(false);
  let [form1] = Form.useForm();
  let [userId, setUserId] = useState('')
  let [roleId, setRoleId] = useState('')
  const [plainOptions, setPlainOptions] = useState<string[]>([]);
  const [checkedList, setCheckedList] = useState<CheckboxValueType[]>([]);
  let [allRolesList, setAllRolesList] = useState<UserModel[]>([])
  // let [assignRoles, setAssignRoles] = useState<UserModel[]>([])
  const onChange = async (list: CheckboxValueType[]) => {
    setCheckedList(list);
    setIndeterminate(!!list.length && list.length < plainOptions.length);
    setCheckAll(list.length === plainOptions.length);
    let roleId = allRolesList.filter(item => {
      return list.includes(item.roleName)
    }).map(item => item.id).join()
    setRoleId(roleId)
  };

  const onCheckAllChange = (e: CheckboxChangeEvent) => {
    setCheckedList(e.target.checked ? plainOptions : []);
    setIndeterminate(false);
    setCheckAll(e.target.checked);
  };
  let okHandler = async () => {
    setIsOpen(false)
    await doAssign(userId, roleId)
    getUserListAsync()
  }

  let cancelHandler = () => {
    setIsOpen(false)
  }

  let columns: ColumnsType<UserModel> = [
    {
      title: '序号',
      render: (value: any, row: any, index: number) => {
        return index + 1
      }
    },
    {
      title: '用户名',
      dataIndex: 'username',
    },
    {
      title: '用户昵称',
      dataIndex: 'nickName',
    },
    {
      title: '角色列表',
      dataIndex: 'roleName',
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreate'
    },
    {
      title: '更新时间',
      dataIndex: 'gmtModified'
    },
    {
      title: '操作',
      render: (value: any, row: any, index: number) => {
        return (
          <Space>
            {/* 分配角色 */}
            <Button
              icon={<UserOutlined />}
              size="middle"
              disabled={value.type === 2}
              style={{ backgroundColor: 'blue', color: '#fff' }}
              onClick={ async () => {
                setIsOpen(true)
                setUserId(value.id)
                form1.setFieldsValue({
                  ...value
                })
                let result = await toAssign(value.id)
                setAllRolesList(result.allRolesList)
                setPlainOptions(result.allRolesList.map(item => item.roleName))
                setCheckedList(result.assignRoles.map(item => item.roleName))
              }}
            ></Button>
            {/* 编辑 */}
            <Button
              icon={<FormOutlined />}
              size="middle"
              disabled={value.level === 1}
              style={{ backgroundColor: 'blue', color: '#fff' }}
              onClick={() => {
                showModal()
                form.setFieldsValue({
                  ...value
                })
                setFormData({
                  ...value
                })
              }}
            ></Button>
            {/* 删除 */}
            <Button
              icon={<DeleteOutlined />}
              size="middle"
              disabled={value.level == "1"}
              style={{ backgroundColor: 'red', color: '#fff' }}
              onClick={async () => {
                await remove(value.id)
                getUserListAsync();
              }}
            ></Button>
          </Space>
        )
      },
    }
  ]

  let showTotal: PaginationProps['showTotal'] = total => `共有 ${total} 条`;
  
  let getUserListAsync = async () => {
    let result = await getUserList(page, limit, username)
    setTotal(result.total)
    setUserList(result.items)
  }

  let search = () => {
    getUserListAsync();
  }
  let reset = () => {
    setUsername('')
    getUserListAsync();
  }
  useEffect(() => {
    getUserListAsync();
  }, [page, limit])

  let rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: UserModel[]) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    getCheckboxProps: (record: UserModel) => (
      {
      // disabled: record.name === 'Disabled User', // Column configuration not to be checked
      // name: record.name,
    }),
  };
  return (
    <Card>
      <Input style={{ width: '200px'}} value={username} onChange={changeHandler} ></Input>
      <Button 
        className='ml-20 mr-10' 
        style={{ background: '#79bbff', color: 'white' }} 
        icon={<SearchOutlined />} 
        onClick={search}
      >查询</Button>
      <Button onClick={reset} >清空</Button>
      <div className='mt-20 mb-20' >
        <Button style={{ background: '#79bbff', color: 'white' }} onClick={addHandler} >添加</Button>
        <Button>批量删除</Button>
      </div>
      <Table 
        rowSelection={{
          type: selectionType,
          ...rowSelection,
        }}
        columns={columns}
        bordered
        dataSource={userList}
        rowKey='id'
        pagination={false}
      ></Table>
      <Pagination
        className='mt-20'
        current={page}
        pageSize={limit}
        total={total}
        showSizeChanger
        showQuickJumper
        pageSizeOptions={[3, 5, 10, 15]}
        onChange={(page, pageSize) => {
          setPage(page)
          setLimit(pageSize)
        }}
        showTotal={showTotal}
      />
      <Modal
        title="添加菜单"
        visible={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确认"
        cancelText="取消"
      >
        <Form
          form={form}
          {...layout}
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[{ required: true, message: '请输入名称' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="用户昵称"
            name="nickName"
          >
            <Input />
          </Form.Item>
          { inputVisible && <Form.Item
            label="用户密码"
            name="password"
            rules={[{ required: true, message: '请输入功能权限值' }]}
          >
            <Input />
          </Form.Item> }
        </Form>
      </Modal>
      <Modal
        title="设置角色"
        visible={isOpen}
        onOk={okHandler}
        onCancel={cancelHandler}
        okText="保存"
        cancelText="取消"
      >
        <Form
          form={form1}
          {...layout}
        >
          <Form.Item
            label="用户名"
            name="username"
          >
            <Input disabled />
          </Form.Item>

          <Form.Item
            label="角色列表"
            name="roleName"
          >
            <Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll}>
              全选
            </Checkbox>
            <Divider />
            <CheckboxGroup options={plainOptions} value={checkedList} onChange={onChange} />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  )
}
